import { initBaseDao } from '../../sdk';
import { ERROR_LOG_DB_NAME } from '../../db';
import { getToday } from '..';

export const logFn = (context: IContext<IParams>) => {
  const data = JSON.stringify(context?.data || context)
  console.log(
    `---------函数: ${context.fcName || ''}.${
      context?.cloud?.dataspace?.context?.handler || context.handler
    }------------`
  )
  console.log(`---------请求参数: ${data}------------`)
}

// 记录错误日志
export const recordErrorLog = async (
  context: IContext<IParams>,
  baseInfos: IControllerInfos,
  errorMsg: string,
  stack: string
) => {
  const { openId } = context
  const { activityId, pageId } = context.data || {}
  const { userInfo } = baseInfos
  const { userNick } = userInfo || {}
  const logdao: IBaseDao = initBaseDao(context, ERROR_LOG_DB_NAME)
  const functionName: string = `${context.fcName || ''}.${
    context?.cloud?.dataspace?.context?.handler || context.handler
  }`
  return await logdao.insertOne({
    openId,
    activityId,
    pageId,
    errorMsg,
    errorStack: stack,
    functionName,
    userNick,
    fcInvokeId: context.fcInvokeId,
    params: context.data,
    createTime: Date.now(),
    createDay: getToday(),
  })
}